<template>
  <div class="favorites-page">
    <div class="page-header">
      <h2>我的收藏</h2>
      <p>共 {{ favorites.length }} 件收藏商品</p>
    </div>

    <div class="favorites-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <i class="fa fa-exclamation-circle"></i>
        <p>{{ errorMessage }}</p>
        <button @click="fetchFavorites" class="retry-btn">重试</button>
      </div>

      <!-- 空状态 -->
      <div v-else-if="favorites.length === 0" class="empty-state">
        <i class="fa fa-heart-o"></i>
        <p>暂无收藏商品</p>
        <router-link to="/" class="go-shopping">去购物</router-link>
      </div>

      <!-- 收藏列表 -->
      <div v-else class="favorites-list">
        <div v-for="item in favorites" :key="item.favorite_id" class="favorite-item">
          <div class="goods-image">
            <img
              :src="item.goods_info?.goods_cover_img || 'https://via.placeholder.com/200'"
              :alt="item.goods_info?.goods_name"
            />
          </div>
          <div class="goods-info">
            <h3 class="goods-name">{{ item.goods_info?.goods_name || '商品已下架' }}</h3>
            <p class="goods-price">¥{{ item.goods_info?.goods_price || '0.00' }}</p>
            <p class="favorite-date">收藏时间: {{ formatDate(item.create_time) }}</p>
          </div>
          <div class="actions">
            <button class="view-btn" @click="viewGoods(item.goods_id)">查看商品</button>
            <button class="remove-btn" @click="removeFavorite(item.favorite_id, item.goods_id)">
              <i class="fa fa-trash"></i> 取消收藏
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/useAuthStore'
import { favoritesApi, type FavoriteItem } from '@/api/favorites'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const authStore = useAuthStore()

const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const favorites = ref<FavoriteItem[]>([])

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// 获取收藏列表
const fetchFavorites = async () => {
  try {
    loading.value = true
    error.value = false
    console.log('正在获取收藏列表...')
    const response = await favoritesApi.getFavoritesList()
    console.log('收藏API响应:', response)

    // 适配后端返回的数据结构
    const favoritesData = Array.isArray(response) ? response : response.results || []
    // 转换数据结构以匹配前端期望的格式 - 修复类型分配问题
    favorites.value = favoritesData.map((item: any) => ({
      favorite_id: item.favorite_id || item.id || 0,
      goods_id: item.goods_id || item.goods?.goods_id || 0,
      goods_info: {
        goods_id: item.goods_id || item.goods?.goods_id || 0,
        goods_name: item.goods_info?.goods_name || item.goods?.goods_name || '未知商品',
        goods_price: item.goods_info?.goods_price || item.goods?.goods_price || '0.00',
        goods_cover_img:
          item.goods_info?.goods_cover_img ||
          item.goods?.goods_cover_img ||
          'https://via.placeholder.com/200',
        goods_status: item.goods_info?.goods_status || item.goods?.goods_status || 0,
      },
      create_time: item.create_time || item.created_time || new Date().toISOString(),
    }))
  } catch (err) {
    error.value = true
    errorMessage.value = err instanceof Error ? err.message : '获取收藏列表失败'
    console.error('获取收藏列表失败:', err)
  } finally {
    loading.value = false
    console.log('加载状态结束，loading:', loading.value)
  }
}

// 查看商品
const viewGoods = (goodsId: number) => {
  router.push(`/product/${goodsId}`)
}

// 取消收藏
const removeFavorite = async (favoriteId: number, goodsId: number) => {
  try {
    await ElMessageBox.confirm('确定要取消收藏这个商品吗？', '取消收藏', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await favoritesApi.removeFromFavorites(goodsId)
    ElMessage.success('已取消收藏')

    // 从列表中移除
    favorites.value = favorites.value.filter((item) => item.favorite_id !== favoriteId)
  } catch (err) {
    if (err !== 'cancel') {
      console.error('取消收藏失败:', err)
      ElMessage.error('取消收藏失败')
    }
  }
}

onMounted(() => {
  if (!authStore.isAuthenticated()) {
    router.push('/login')
    return
  }
  fetchFavorites()
})
</script>

<style scoped lang="scss">
.favorites-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .page-header {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    h2 {
      font-size: 24px;
      margin-bottom: 5px;
      color: #333;
    }

    p {
      color: #666;
      margin: 0;
    }
  }

  .loading-container,
  .error-container,
  .empty-state {
    text-align: center;
    padding: 80px 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    i {
      font-size: 48px;
      margin-bottom: 20px;
    }

    p {
      color: #666;
      margin-bottom: 20px;
      font-size: 16px;
    }
  }

  .loading-container {
    i {
      color: #409eff;
    }
  }

  .error-container {
    i {
      color: #f56c6c;
    }
  }

  .empty-state {
    i {
      font-size: 64px;
      color: #ccc;
      margin-bottom: 20px;
    }

    p {
      font-size: 18px;
      color: #999;
      margin-bottom: 30px;
    }

    .go-shopping {
      display: inline-block;
      padding: 12px 24px;
      background-color: #409eff;
      color: white;
      text-decoration: none;
      border-radius: 4px;
      font-size: 16px;
      transition: all 0.3s;

      &:hover {
        background-color: #3080e0;
      }
    }
  }

  .favorites-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 20px;

    .favorite-item {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      transition: transform 0.2s ease;

      &:hover {
        transform: translateY(-2px);
      }

      .goods-image {
        width: 100%;
        height: 200px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease;

          &:hover {
            transform: scale(1.05);
          }
        }
      }

      .goods-info {
        padding: 15px;

        .goods-name {
          font-size: 16px;
          margin-bottom: 10px;
          color: #333;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .goods-price {
          color: #e4393c;
          font-weight: bold;
          font-size: 18px;
          margin-bottom: 8px;
        }

        .favorite-date {
          color: #999;
          font-size: 12px;
          margin: 0;
        }
      }

      .actions {
        padding: 15px;
        border-top: 1px solid #eee;
        display: flex;
        gap: 10px;

        .view-btn,
        .remove-btn {
          flex: 1;
          padding: 8px 12px;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          font-size: 14px;
          transition: all 0.2s;
        }

        .view-btn {
          background-color: #409eff;
          color: white;

          &:hover {
            background-color: #3080e0;
          }
        }

        .remove-btn {
          background-color: #f5f5f5;
          color: #666;
          border: 1px solid #ddd;

          &:hover {
            background-color: #ffebeb;
            color: #f56c6c;
            border-color: #f56c6c;
          }
        }
      }
    }
  }

  .retry-btn {
    padding: 12px 30px;
    background-color: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #e6e6e6;
    }
  }

  .spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 20px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #409eff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}

@media (max-width: 768px) {
  .favorites-page {
    padding: 10px;

    .favorites-list {
      grid-template-columns: 1fr;

      .favorite-item {
        .actions {
          flex-direction: column;
        }
      }
    }
  }
}
</style>
